
package tetris.gui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;

import javax.swing.JPanel;

import tetris.board.Board;
import tetris.pieces.AbstractShape;

/**
 * The preview of the next Tetris piece.
 * 
 * @author Agari NLN (agarin@uw.edu)
 * @version 2.8
 * 
 */
public class Preview extends JPanel
{

  /**
   * This is here to avoid warnings.
   */
  private static final long serialVersionUID = 1L;

  /**
   * The number of how many times a piece(represented by points) are being
   * magnified for eye to see.
   */
  private static final int MY_MAGNIFIER = 10;
  
  /**
   * The default width.
   */
  private static final int DEFAULT_WIDTH = 100;
  
  /**
   * The default height.
   */
  private static final int DEFAULT_HEIGHT = 20;

  /**
   * My Tetris board, logic.
   */
  private final Board my_tetris_board;

  /**
   * Constructing the preview of the next Tetris piece.
   * 
   * @param the_board the Tetris board, logic.
   */
  public Preview(final Board the_board)
  {
    super();
    my_tetris_board = the_board;
    setBackground(Color.WHITE);
    setPreferredSize(new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT));
  }

  /**
   * Draw the preview board and also preview the next falling piece.
   * 
   * @param the_graphics the graphic where the drawn pieces are at.
   */
  public void paintComponent(final Graphics the_graphics)
  {
    super.paintComponent(the_graphics);
    final Graphics2D g2d = (Graphics2D) the_graphics;
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    final AbstractShape shape = my_tetris_board.getNextPiece();

    final Point[] shapePositions = my_tetris_board.getNextPiece().blockPositionsNoBoard();
    final Point[] current_shapePositions =
        my_tetris_board.getCurrentPiece().blockPositionsNoBoard();

    if (my_tetris_board.getCurrentPiece().myPosition().y >= 0)
    {
      for (int i = 0; i < shapePositions.length; i++)
      {
        g2d.setColor(shape.getColor());
        g2d.fillRect((shapePositions[i].x) * MY_MAGNIFIER, (shapePositions[i].y) *
                                                 MY_MAGNIFIER, MY_MAGNIFIER, MY_MAGNIFIER);
      }
    }
    else
    {
      for (int i = 0; i < current_shapePositions.length; i++)
      {
        g2d.setColor(my_tetris_board.getCurrentPiece().getColor());
        g2d.fillRect((current_shapePositions[i].x) * MY_MAGNIFIER,
                     (current_shapePositions[i].y) * MY_MAGNIFIER, MY_MAGNIFIER, MY_MAGNIFIER);
      }
    }
    repaint();
  }

}
